package com.zb.mail.util;

import com.zb.mail.pojo.User;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendMailUtil implements Runnable{

    private static final String FROM = "594507903@qq.com";
    private static final String USERNAME = "594507903@qq.com";
    private static final String PASSWORD = "wtacdribubspbdhh";
    private static final String HOST = "smtp.qq.com";

    private User user;

    public SendMailUtil(User user){
        this.user = user;
    }


    @Override
    public void run() {

        Properties properties = new Properties();
        properties.setProperty("mail.host", HOST);
        properties.setProperty("mail.transport.protocol","smtp");
        properties.setProperty("mail.smtp.auth","true");

        Transport transport = null;

        try {
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(USERNAME, PASSWORD);
                }
            });
            session.setDebug(true);
            transport = session.getTransport();
            transport.connect();

            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(FROM));
            message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(user.getEmail()));
            message.setSubject("注册成功");
            message.setContent("您好，感谢您注册本网站，您的账号为：" + user.getUsername() + ",您的密码为：" + user.getPassword() + ",请妥善保管！", "text/html;charset=utf-8");
            message.saveChanges();

            transport.sendMessage(message, message.getAllRecipients());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert transport != null;
                transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }

    }
}
